/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.huize.ladon.apm.common.util;

/**
 * 描述: IP地址工具类
 *
 * @author tianyuliang
 * @version $Id: IPv4Utils.java, v0.1 2020/12/5
 */
public class IPv4Utils {


    /**
     * 将 字符串IP 转化为 数字型IP
     * 例如 114.114.114.114 转化为 1920103026
     */
    public static long ipToLong(String strIp) {
        long[] ip = new long[4];

        // 先找到IP地址字符串中.的位置
        int position1 = strIp.indexOf(".");
        int position2 = strIp.indexOf(".", position1 + 1);
        int position3 = strIp.indexOf(".", position2 + 1);

        // 将每个.之间的字符串转换成整型
        ip[0] = Long.parseLong(strIp.substring(0, position1));
        ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));
        ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));
        ip[3] = Long.parseLong(strIp.substring(position3 + 1));

        long ipLong = (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
        return ipLong;
    }


    /**
     * 将 数字型IP 转化为 字符串IP
     * 例如 1920103026  转化为 114.114.114.114
     */
    public static String longToIp(long longIp) {
        StringBuffer sb = new StringBuffer();
        // 直接右移24位
        sb.append(String.valueOf((longIp >>> 24)));
        sb.append(".");

        // 将高8位置0，然后右移16位
        sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));
        sb.append(".");

        // 将高16位置0，然后右移8位
        sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));
        sb.append(".");

        // 将高24位置0
        sb.append(String.valueOf((longIp & 0x000000FF)));
        return sb.toString();
    }


    public static void main(String[] args) throws Exception {
        String ipStr = "114.114.114.114";
        long longIp = ipToLong(ipStr);
        System.out.println("IP字符串=" + ipStr + ", IP整数=" + longIp);

        String strIp = longToIp(1920103026L);
        System.out.println("IP整数=" + longIp + ", IP字符串=" + strIp);
    }


}